package com.example.demo.config.producer;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author yongen
 * @description: 生产者配置
 * @date 2022/2/9 2:18 PM
 */
@Configuration
@Slf4j
public class DefaultProducerConfig {

  @Resource
  private RocketMQProducerProperties producerProperties;

  @Bean
  @Primary
  public DefaultMQProducer defaultProducer() throws MQClientException {
    DefaultMQProducer producer = new DefaultMQProducer(producerProperties.getGroup());
    producer.setNamesrvAddr(producerProperties.getNamesrvAddr());
    producer.setVipChannelEnabled(false);
    producer.setRetryTimesWhenSendAsyncFailed(producerProperties.getRetryTimesWhenSendAsyncFailed());
    producer.setSendMsgTimeout(producerProperties.getSendMsgTimeout());
    producer.start();
    log.info("RocketMQ Producer 初始化成功: {}", JSONUtil.parse(producerProperties));
    return producer;
  }
}
